import debounce from "@/utils/debounce";
import { onMounted, onUnmounted, ref } from "vue";
interface Options {
  onBottom?: () => void;
  onTop?: () => void;
  onChange?: (scrollTop: number) => void;
}
export default function useScroll(options: Options = {}) {
  const { onTop, onBottom, onChange } = options;
  const container = ref<HTMLElement>();

  let lastChildHeight = 0;
  let lastTop = 0;

  const onScroll = (e: any) => {
    onChange?.(e.target.scrollTop);
    debounce(
      () => {
        lastTop = e.target.scrollTop;
        lastChildHeight = e.target.scrollHeight;
        // ;
        if (e.target.scrollTop <= 50) {
          onTop?.();
        }
        if (
          e.target.scrollTop >=
          e.target.scrollHeight - e.target.offsetHeight
        ) {
          onBottom?.();
        }
      },
      500,
      false
    );
  };
  const toTop = debounce((top = 0) => {
    if (container.value?.scrollTop) {
      container.value.scrollTop = top;
    }
  });

  const toBottom = (isFirst: boolean = true) => {
    if (container.value) {
      if (isFirst) {
        container.value.scrollTop = container.value.scrollHeight - 50;
      } else {
        container.value.scrollTop =
          container.value.scrollHeight - lastChildHeight - 50;
      }
    }
  };

  const off = () => {
    container.value?.removeEventListener("scroll", onScroll);
  };
  const update = () => {
    if (!container.value) {
      return;
    }
    container.value?.addEventListener("scroll", onScroll);
  };
  onMounted(() => {
    // container.value?.addEventListener("scroll", onScroll);
  });

  onUnmounted(() => {
    // container.value?.removeEventListener("scroll", onScroll);
  });

  return { container, update, off, toTop, toBottom };
}
